package com.jlh.viewer.base64;

import java.io.*;

/**
 * Created by jlh
 * On 2017/4/5 0005.
 */
public class Main {

    public static void main(String[] args) {
        byte[] data = null;
        byte[] buffer= new byte[1024];
        File file = new File("D:\\test\\orignal.jpg");
        try (FileInputStream in = new FileInputStream(file);ByteArrayOutputStream byteArrayOutputStream= new ByteArrayOutputStream(1024)){
            int size;
            while (-1 != (size = in.read(buffer))){
                byteArrayOutputStream.write(buffer,0,size);
            }
            data=byteArrayOutputStream.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String encode= Base64Utils.encode(data);
        //存储

        File codeFile = new File("D:\\test\\code.txt");
        if (codeFile.exists())
            codeFile.delete();
        try {
            codeFile.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try(FileWriter fileWriter = new FileWriter(codeFile)) {
            fileWriter.write(encode);
            fileWriter.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //输出解密图片
        File decodeFile = new File("D:\\test\\decode.jpg");
        if (decodeFile.exists())
            decodeFile.delete();
        try {
            decodeFile.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String codeContext= null;
        try (FileReader reader = new FileReader(codeFile)){
            StringBuilder stringBuffer =new StringBuilder();
            char[] buf = new char[1024];
            while (-1 != reader.read(buf)){
                stringBuffer.append(buf);
            }
            codeContext=stringBuffer.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }

        byte[] decodeByte=Base64Utils.decode(codeContext);
        try (FileOutputStream out =new FileOutputStream(decodeFile)) {
            out.write(decodeByte);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
